package com.googlecode.bipol.war.services;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import org.apache.log4j.Logger;
import com.googlecode.bip.dao.DAOFactory;
import com.googlecode.bip.dao.QuestionDAO;
import com.googlecode.bip.dao.TopicDAO;
import com.googlecode.bip.dao.UserValueDAO;
import com.googlecode.bip.entity.IQuestion;
import com.googlecode.bip.entity.IQuestionValue;
import com.googlecode.bip.entity.ISurveyEntry;
import com.googlecode.bip.entity.ITopic;
import com.googlecode.bip.entity.IUserValue;
import com.googlecode.bip.entity.impl.QuestionValue;
import com.googlecode.bipol.war.entity.ISurvey;
//import com.googlecode.bipol.war.entity.QuestionValue;
import com.googlecode.bipol.war.entity.impl.ISurveyImpl;
import com.googlecode.bipol.war.session.IBipSession;

/**
 * Default implementation of {@link SurveyManager}
 */
public class SurveyManager2Impl implements SurveyManager2, Serializable {
    private final static long serialVersionUID = 4L;
    private final static Logger logger = Logger.getLogger(SurveyManager2Impl.class);
    private IBipSession bipSession;

    public SurveyManager2Impl( final IBipSession bipSession )
    {
        this.bipSession = bipSession;
    }

    @Override
    public ISurvey fetchSurvey( final String idlocal )
        throws ServiceException
    {
        try {
            //List<ISurveyEntry> survey = new ArrayList<ISurveyEntry>();
            final ISurveyImpl           survey          = new ISurveyImpl();
            final List<ISurveyEntry>    surveyEntries   = survey.getSurveyEntries();

            final TopicDAO      topicDAO        = DAOFactory.getDAOFactory().getTopicDAO();
            final QuestionDAO   questionDAO     = DAOFactory.getDAOFactory().getQuestionDAO();
            final UserValueDAO  userValueDAO    = DAOFactory.getDAOFactory().getUserValueDAO();

            if( bipSession.getGenericUser() == null ) {
                logger.fatal( "iUser is null ! (new user)" );
                }

            final Timestamp userdate = bipSession.getUserDate();
            final int       userId   = bipSession.getGenericUser().getIdUser();

//            // Add the metadata to survey
//            ISurveyMetaData metaData = new SurveyMetaData(userdate);
//            survey.add(metaData);
    //
//            int numberOfQuestions = 0;
//            int numberOfAnswers = 0;

            List<ITopic> topics = topicDAO.getAllTopics();

            for( ITopic t : topics ) {
                if( idlocal.equals( t.getIdLocal() ) ) {
                    if( t.getIdTopic() >= 0 ) {
//                        survey.add(t);
                        surveyEntries.add( t );

                        List<IQuestion> questions = questionDAO.findQuestions( t, t.getIdLocal() );

                        for( IQuestion q : questions ) {
                            // Is there an existing UserValue ?
                            IUserValue userValue = userValueDAO.getUserValue(
                                    userId,
                                    q.getIdQuestion(),
                                    userdate
                                    );
                            IQuestionValue questionValue = new QuestionValue( q, userValue );

//                            if( userValue.getUserValue() != null ) {
//                                numberOfAnswers++;
//                                System.out.println(numberOfAnswers);
//                            }
//                            survey.add( questionValue );
                            surveyEntries.add( questionValue );
//                            numberOfQuestions++;
                            }
                        }
                    }
                }

//          if( logger.isDebugEnabled() ) {
//              logger.debug( "numberOfAnswers = " + numberOfAnswers );
//              }
  //
//          metaData.setNumberOfAnswers(numberOfAnswers);
//          metaData.setNumberOfQuestions(numberOfQuestions);

          return survey;
        }
        catch( Exception e ) {
            logger.fatal("fetchSurvey error", e);

            throw new ServiceException("Error when getting survey: " + e.getMessage(), e);
            }
    }

    @Override
    public ISurvey postSurvey( final ISurvey survey ) throws ServiceException
    {
        try {
//            final IGenericUser  iUser   = bipSession.getGenericUser();
            final UserValueDAO  dao     = DAOFactory.getDAOFactory().getUserValueDAO();

//            ISurveyMetaData metaData = null;
//
//            // Get back meta data
//            for (ISurveyEntry entry : survey) {
//                if (entry.isISurveyMetaData()) {
//                    metaData = ISurveyMetaData.class.cast(entry);
//                    break;
//                }
//            }

            // Save UserValues
//            int numberOfQuestions = 0;
//            int numberOfAnswers = 0;

            for( ISurveyEntry entry : survey.getSurveyEntries() ) {
                if(entry.isIQuestion() ) {
                    //IQuestion q = IQuestion.class.cast(entry);
                    IQuestionValue q = IQuestionValue.class.cast( entry );

                    if (q.getUserValue() != null) {
                        dao.updateUserValue( q );
//                        numberOfAnswers++;
                    }
//                    numberOfQuestions++;
                }
                // else ITopic
            }
//            metaData.setNumberOfAnswers(numberOfAnswers);
//            metaData.setNumberOfQuestions(numberOfQuestions);
        } catch (Exception e) {
            logger.fatal("postSurvey error", e);
            throw new ServiceException("Error when saving survey: "
                    + e.getMessage(), e);
        }

        return survey;
    }

}
